/*
 * @Description: 移交申请单列表
 * @Author: Rfan
 * @Date: 2022-05-12 15:03:45
 * @LastEditTime: 2022-05-30 12:13:24
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table, Tag } from 'antd';
import { useDictionaryContext } from '../contexts/DictionaryContext';
import { useFormatMessage } from '@/utils/intlHelpers';
import type { IPageQuery, IPageResolve } from '@/interfaces/global';
import EditDictionaryItemDialog from './dialogs/EditDictionaryItem';

const { Column } = Table;

const PageList = () => {
  const {
    selectDictionary,
    dictionaryItemList,
    selectItems,
    setSelectedItem,
    getDicItemListByPage,
    deleteDicItemFunc,
    stateFilter
  } = useDictionaryContext();
  const formatMessage = useFormatMessage();

  // 表格加载
  const [loading, setLoading] = useState(false);
  // 总条目数
  const [total, setTotal] = useState(0);
  // 表格请求参数
  const [listQuery, setListQuery] = useState<IPageQuery>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });

  // 编辑弹窗
  const [editVisible, setEditVisible] = useState(false);

  // 编辑弹窗数据
  const [activeEditData, setActiveEditData] = useState({});

  useEffect(() => {
    if (selectDictionary?.id) {
      setListQuery((state) => ({
        ...state,
        param: {
          typeId: selectDictionary.id
        }
      }));
    }
  }, [selectDictionary]);

  useEffect(() => {
    if (listQuery && listQuery.param && JSON.stringify(listQuery.param) !== '{}') {
      setLoading(true);
      getDicItemListByPage(listQuery).then((res: IPageResolve) => {
        setLoading(false);
        setTotal(res.totalCount);
      });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectedItem(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  /**
   * @description: 打开编辑弹窗
   * @param {any} data 选中的条目
   */
  const showEditDialog = (data: any) => {
    setActiveEditData(data);
    setEditVisible(true);
  };
  /**
   * @description: 关闭编辑弹窗
   */
  const hideEditDialog = () => {
    setEditVisible(false);
  };

  return (
    <>
      <Table
        dataSource={dictionaryItemList}
        loading={loading}
        rowKey="id"
        rowSelection={rowSelection}
        bordered
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="序号" dataIndex="id" key="id" align="center" />
        <Column title="名称" dataIndex="name" key="name" align="center" />
        <Column title="代码" dataIndex="code" key="code" align="center" />
        <Column title="值" dataIndex="value" key="value" align="center" />
        <Column
          title="状态"
          dataIndex="isValid"
          key="isValid"
          align="center"
          render={(isValid) => <Tag color="blue">{stateFilter(isValid)}</Tag>}
        />
        <Column title="描述" dataIndex="remark" key="remark" align="center" />
        <Column
          title={formatMessage('tableAction')}
          key="action"
          align="center"
          render={(_text, record: any) => (
            <Space>
              <Button
                type="link"
                size="small"
                onClick={() => {
                  showEditDialog(record);
                }}
              >
                编辑
              </Button>
              <Button
                type="link"
                size="small"
                danger
                onClick={() => {
                  deleteDicItemFunc(record.id);
                }}
              >
                删除
              </Button>
            </Space>
          )}
        />
      </Table>
      {useMemo(
        () => (
          <EditDictionaryItemDialog
            visible={editVisible}
            data={activeEditData}
            onClose={hideEditDialog}
          />
        ),
        [editVisible]
      )}
    </>
  );
};

export default PageList;
